package be.fw.mana;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.swing.JOptionPane;

import jxl.Workbook;
import jxl.format.Colour;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class ManaReader
{
    private final static int TEAMNAME_LENGTH = 23;
    private final static int PLAYERNAME_LENGTH = 26;
    private final static int PLAYERS_PER_TEAM = 20;
    private final static int NUMBER_OF_TEAMS = 64;
    private final static int NUMBER_OF_EUROPEAN_TEAMS = 136;

    private WritableWorkbook workbook;

    private int longestPlayerName = 0;
    private int longestTeamName = 0;
    
    private final WritableFont fontGoalie = new WritableFont(WritableFont.ARIAL);
    private final WritableFont fontDefender = new WritableFont(WritableFont.ARIAL);
    private final WritableFont fontMidfielder = new WritableFont(WritableFont.ARIAL);
    private final WritableFont fontAttacker = new WritableFont(WritableFont.ARIAL);
    
    private WritableCellFormat formatGoalie;
    private WritableCellFormat formatDefender;
    private WritableCellFormat formatMidfielder;
    private WritableCellFormat formatAttacker;

    public ManaReader()
    {
        try
        {
        	formatGoalie = new WritableCellFormat (fontGoalie);
        	formatDefender = new WritableCellFormat (fontDefender);
        	formatMidfielder = new WritableCellFormat (fontMidfielder);
        	formatAttacker = new WritableCellFormat (fontAttacker);
        	
        	fontGoalie.setColour(Colour.GREEN);
        	fontDefender.setColour(Colour.BLUE);
        	fontMidfielder.setColour(Colour.ORANGE);
        	fontAttacker.setColour(Colour.RED);
        	
            workbook = Workbook.createWorkbook(new File("mana.xls"));

            FileInputStream fis = new FileInputStream("MANA.DAT");
            league(fis);
            europa(fis);
            fis.close();
            workbook.write();
            workbook.close();
            System.out.println("longestPlayerName = " + longestPlayerName);
            System.out.println("longestTeamName = " + longestTeamName);
            JOptionPane.showMessageDialog(null, "Reading of MANA.DAT completed.\n\nA mana.xls Excel file has been written in the same directory as this tool.\nThis file can be edited in Excel, and re-imported with this tool.", "Import OK :-)", JOptionPane.INFORMATION_MESSAGE);
        }
        catch (FileNotFoundException e)
        {
            JOptionPane.showMessageDialog(null, "Import failed.\n\nBe sure to place this tool in your BMP/TM directory where MANA.DAT resides.", "Import FAILED :-(", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
        catch (IOException e)
        {
            JOptionPane.showMessageDialog(null, "Import failed.\n\nBe sure to place this tool in your BMP/TM directory where MANA.DAT resides.", "Import FAILED :-(", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
        catch (RowsExceededException e)
        {
            JOptionPane.showMessageDialog(null, "Import failed.\n\nBe sure to place this tool in your BMP/TM directory where MANA.DAT resides.", "Import FAILED :-(", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
        catch (WriteException e)
        {
            JOptionPane.showMessageDialog(null, "Import failed.\n\nBe sure to place this tool in your BMP/TM directory where MANA.DAT resides.", "Import FAILED :-(", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
    }

    /**
     * Inlezen europese teams + spelers
     *
     * @param fis
     * @throws IOException
     * @throws WriteException
     * @throws RowsExceededException
     */
    private void europa(FileInputStream fis) throws IOException, RowsExceededException, WriteException
    {
        WritableSheet sheet = workbook.createSheet("Europe", workbook.getNumberOfSheets());
        for (int i = 0; i < NUMBER_OF_EUROPEAN_TEAMS; i++)
        {
            byte[] europeTeam = new byte[TEAMNAME_LENGTH];
            for (int j = 0; j < TEAMNAME_LENGTH; j++)
            {
                europeTeam[j] = (byte) fis.read();
            }

            String sEuropeTeam = new String(europeTeam);
            teamLength(sEuropeTeam);
            System.out.println("sEuropeTeam = '" + sEuropeTeam + "'");
            sheet.addCell(new Label(0, i, sEuropeTeam.trim()));
        }
    }

    /**
     * Check of dit de langste teamnaam tot nu toe is
     * @param teamName
     */
    private void teamLength(String teamName)
    {
        if(teamName.trim().length() > longestTeamName) longestTeamName = teamName.trim().length();
    }

    /**
     * Inlezen league teams
     *
     * @param fis
     * @throws IOException
     * @throws WriteException
     * @throws RowsExceededException
     */
    private void league(FileInputStream fis) throws IOException, RowsExceededException, WriteException
    {
        // first skip 984 bytes long header
        for (int i = 0; i < 984; i++)
        {
            fis.read();
        }

        for (int i = 0; i < NUMBER_OF_TEAMS; i++)
        {
            System.out.println("reading team: " + i);
            readBlock(fis, i);
        }
    }

    /**
     * Read 1 block
     *
     * @param fis
     * @param index
     * @throws IOException
     * @throws WriteException
     * @throws RowsExceededException
     */
    private void readBlock(FileInputStream fis, int index) throws IOException, RowsExceededException, WriteException
    {
        byte[] team = new byte[TEAMNAME_LENGTH];
        for (int i = 0; i < TEAMNAME_LENGTH; i++)
        {
            team[i] = (byte) fis.read();
        }

        String sTeam = new String(team);
        teamLength(sTeam);
        System.out.println("sTeam = '" + sTeam + "'");
        WritableSheet sheet = workbook.createSheet(sTeam.trim(), workbook.getNumberOfSheets());
        sheet.addCell(new Label(0, 0, sTeam.trim()));
        for (int i = 0; i < PLAYERS_PER_TEAM; i++)
        {
            byte[] player = new byte[PLAYERNAME_LENGTH];
            for (int j = 0; j < PLAYERNAME_LENGTH; j++)
            {
                player[j] = (byte) fis.read();
            }
            String sPlayer = new String(player);
            if(sPlayer.trim().length() > longestPlayerName)
            {
                longestPlayerName = sPlayer.trim().length();
                System.out.println("longest = " + longestPlayerName + " : " + sPlayer);
            }
            System.out.println("   sPlayer = '" + sPlayer + "'");
            if (i <= 1) sheet.addCell(new Label(0, i + 2, sPlayer.trim(), formatGoalie));
            else if (i <= 6) sheet.addCell(new Label(0, i + 2, sPlayer.trim(), formatDefender));
            else if (i <= 14) sheet.addCell(new Label(0, i + 2, sPlayer.trim(), formatMidfielder));
            else sheet.addCell(new Label(0, i + 2, sPlayer.trim(), formatAttacker));
        }
    }
}
